package com.commons.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.commons.exception.BadRequestException;
import com.commons.utils.enums.DataScopeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.List;

/**
 * 获取当前登录用户
 */
public class SecurityUtils {

    private final static Logger LOGGER=LoggerFactory.getLogger(SecurityUtils.class);

    /**
     * 获取当前登录的用户
     */
    public static UserDetails getCurrentUser(){
        UserDetailsService userDetailsService=SpringContextHolder.getBean(UserDetailsService.class);
        return userDetailsService.loadUserByUsername(getCurrentUserName());
    }


    public static String getCurrentUserName(){
        final Authentication authentication=SecurityContextHolder.getContext().getAuthentication();
        if(authentication==null){
            throw  new BadRequestException("当前登录状态过期",HttpStatus.UNAUTHORIZED.value());
        }
        if(authentication.getPrincipal() instanceof UserDetails){
            UserDetails userDetails= (UserDetails) authentication.getPrincipal();
            return userDetails.getUsername();
        }
        throw new BadRequestException("找不到当前登录信息",HttpStatus.UNAUTHORIZED.value());
    }

    /**
     * 获取系统用户ID
     */
    public static Long getCurrentUserId(){
        UserDetails userDetails = getCurrentUser();
        // 将 Java 对象转换为 JSONObject 对象
        JSONObject jsonObject = (JSONObject) JSON.toJSON(userDetails);
        return jsonObject.getJSONObject("user").getLong("id");
    }

    /**
     * 获取当前用户的数据权限
     * @return /
     */
    public static List<Long> getCurrentUserDataScope(){
        UserDetails userDetails=getCurrentUser();
        JSONObject jsonObject= (JSONObject) JSON.toJSON(userDetails);
        JSONArray jsonArray=jsonObject.getJSONArray("dataScopes");
        return JSON.parseArray(jsonArray.toJSONString(),Long.class);
    }

    /**
     * 获取数据权限级别
     * @return 级别
     */
    public static String getDataScopeType(){
        List<Long> dataScopes=getCurrentUserDataScope();
        if(dataScopes.size()!=0){
            return "";
        }
        return DataScopeEnum.ALL.getValue();
    }
}
